//
//  AppDelegate.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/7/27.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit

let TurnToMainContoller = "turnToMainContoller"

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: TurnToMainContoller, object: nil)
        
        print(UserAccount.loadAccount())
        
        setupApperence()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultViewController()
        //测试欢迎界面
//        window?.rootViewController = WelcomeController()
        //测试新特性界面
//        window?.rootViewController = NewFeatureController()
        window?.makeKeyAndVisible()
   
        return true
    }
    //注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func defaultViewController() -> UIViewController {
        if !UserAccount.userLogin {
            return MainViewController()
        }
        
        return isNewUpdate() ? NewFeatureController() : WelcomeController()
    
    }
    
    private func isNewUpdate() -> Bool {
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        NSUserDefaults.standardUserDefaults().synchronize()
        
        return currentVersion > sandboxVersion
    }
    
    
    func switchViewController(n: NSNotification) {
    
        let mainVc = n.object as! Bool
        
        window?.rootViewController = mainVc ? MainViewController() : WelcomeController()
    }
    
    /**
    *  设置外观,一经设置全局有效
    */
    private func setupApperence() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }

}

